# -*- coding: utf-8 -*-
"""
@Time ： 2021/3/19 0:45
@Auth ： 买菠萝凤梨
@File ：read_config.py
@IDE ：PyCharm
@Motto：work steadily

"""
import yaml
import json
from public.log import Log
import os
from configparser import ConfigParser

log = Log()
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

class Config(ConfigParser):
    # 重写 configparser 中的 optionxform 函数，解决 .ini 文件中的 键option 自动转为小写的问题
    def __init__(self, defaults=None):
        ConfigParser.__init__(self, defaults=defaults)

    def optionxform(self, optinstr):
        return optinstr


class Read_conf:

    def __init__(self):
        pass

    def load_yaml(self, yamlfile):
        '''读取yaml文件,请输入yaml文件全名,如data.yaml'''
        try:
            yaml_file = os.path.join(root_path, 'data','yaml', yamlfile)
            log.info('开始加载{}文件'.format(yamlfile))
            with open(yaml_file,encoding='utf-8') as f :
                yamldata = yaml.safe_load(f)
            log.info('{0}文件读取成功,读取的数据为{1}'.format(yamlfile,yamldata))
            return yamldata
        except Exception as e:
            log.error('{0}文件读取失败,请检查文件名称和文件语法,报错:{1}'.format(yamlfile,e))

    def load_ini(self,inifile):
        '''读取ini文件'''
        try:
            ini = os.path.join(root_path,'config',inifile)
            config = Config()
            config.read(ini,encoding='utf-8')
            ini_data = dict(config._sections)
            log.info('{0}文件读取成功,读取的数据为:{1}'.format(ini,ini_data))
            return ini_data
        except Exception as e:
            log.error('文件读取失败，报错：{}'.format(e))


    def load_json(self,jsonfile):
        '''读取json文件'''
        try:
            jsonpath = os.path.join(root_path,'data','json',jsonfile)
            with open(jsonpath,encoding='utf-8') as f:
                data = json.load(f)
                log.info('{0}文件读取成功，读取的数据为{1}'.format(jsonpath,data))
            return data
        except Exception as e:
            log.error('文件读取失败:{}'.format(e))









if __name__ == '__main__':

    root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    print(root_path)
    data = Read_conf().load_yaml('test.yaml')
    print(data)
    data = Read_conf().load_ini('test.ini')
    file = os.path.join(root_path,'data','json','test.json')
    print(file)
    data1 = Read_conf().load_json('test.json')
    print(data1)
    pass


